﻿////Author: Kimmo Forss
namespace SharePoint.ImportExport.StsadmExtension
{
    using System;
    using System.Data;
    using System.Text;
    using Microsoft.SharePoint.StsAdmin;
    using Sharepoint.ImportExport.Extractor;
    using SharePoint.ImportExport.Core;

    public class ExporterExtension : ISPStsadmCommand
    {
        /// <summary>
        /// 
        /// </summary>
        private static string logS;
        
        /// <summary>
        /// This prints the help message
        /// </summary>
        /// <param name="command"></param>
        /// <returns>String to be displayed</returns>
        public string GetHelpMessage(string command)
        {
            StringBuilder helpMsg = new StringBuilder();
            helpMsg.Append("Export content to SharePoint:\r\n");
            helpMsg.Append("\tstsadm.exe\r\n\t-o exportData\r\n");
            helpMsg.Append("\t\t-Url SharePoint site Url\r\n");
            helpMsg.Append("\t\t-directory Directory to export to\r\n");
            helpMsg.Append("\t\t-Owner Site owner (domain account)\r\n");
            helpMsg.Append("\t\t-Contact Site owner email\r\n");
            helpMsg.Append("\r\nOptional:\r\n");
            helpMsg.Append("\t\t-ManagedPath Managed path (Sites etc)\r\n");
            helpMsg.Append("\t\t-SiteName Site name of new site\r\n");
            helpMsg.Append("-List List/Library name to export\r\n");
            helpMsg.Append("-Folder folder name to export\r\n");
            helpMsg.Append("-MinDate Date export threshold (export items newer than)\r\n");
            helpMsg.Append("-MaxDate Date export threshold (export items older than)\r\n");

            helpMsg.Append("-includeSubWebs true|false\r\n");
            helpMsg.Append("-includeUserInformation true|false\r\n");
            helpMsg.Append("-includeVersionInformation true|false\r\n");

            helpMsg.Append("-DateFormat {dateformat} ie \"dd.MM.YYYY\"\r\n");

            helpMsg.Append("-ReportLevel Information|Warning|Error\r\n");

            helpMsg.Append("\r\n\t\tExample : stsadm -o importData -root http://localhost -folder c:\\export -ImportToExistingSite true -ImportToExistingLibrary false -ImportSecurity true -DateFormat dd.MM.YYYY \r\n");
            helpMsg.Append("\t\tAvailable properties : AlternateCssUrl, AlternateHeader\r\n");
            return helpMsg.ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="command"></param>
        /// <param name="keyValues"></param>
        /// <param name="output"></param>
        /// <returns></returns>
        public int Run(string command, System.Collections.Specialized.StringDictionary keyValues, out string output)
        {
            output = string.Empty;
            string dateFormat = String.Empty;
            if (keyValues.ContainsKey("DateFormat"))
            {
                dateFormat = keyValues["DateFormat"];
                Console.WriteLine("Changing the date format to {0}", dateFormat);

                if (dateFormat != System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern)
                {
                    System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = dateFormat;
                }
            }

            DataSet ds = new DataSet("Export Parameters");
            DataTable dt = ds.Tables.Add("Parameters");
            dt.Columns.Add("SiteURL");
            dt.Columns.Add("OutputDirectory");
            dt.Columns.Add("SiteName");
            dt.Columns.Add("List");
            dt.Columns.Add("Owner");
            dt.Columns.Add("Contact");
            dt.Columns.Add("IncludeSubWebs", typeof(bool));
            dt.Columns.Add("ManagedPath");
            dt.Columns.Add("SiteDef");
            dt.Columns.Add("Folder");
            dt.Columns.Add("ExportItemsNewerThan", typeof(System.DateTime));
            dt.Columns.Add("ExportItemsOlderThan", typeof(System.DateTime));
            dt.Columns.Add("ExportDesign", typeof(bool));
            dt.Columns.Add("ExportUsers", typeof(bool));
            dt.Columns.Add("ExportVersions", typeof(bool));
            dt.Columns.Add("ExportDoclibsOnly", typeof(bool));
            dt.Columns.Add("ProcessGalleries", typeof(bool));
            dt.Columns.Add("ExportViews", typeof(bool));

            DataRow newRow = dt.NewRow();

            string siteCollectionRootURL = keyValues["Url"];
            string siteDefinition = String.Empty;
            if (keyValues.ContainsKey("SiteDefinition"))
            {
                siteDefinition = keyValues["SiteDefinition"];
            }

            string managedPath = String.Empty;
            if (keyValues.ContainsKey("ManagedPath"))
            {
                managedPath = keyValues["ManagedPath "];
            }

            string siteName = keyValues["Site"];
            string folderName = keyValues["dirctory"];
            ErrorLevel level = ErrorLevel.Warning;
            if (keyValues.ContainsKey("ReportLevel"))
            {
                level = (ErrorLevel)Enum.Parse(typeof(ErrorLevel), keyValues["ReportLevel"]);
            }

            //// Set values in the columns:
            newRow["SiteURL"] = siteCollectionRootURL;
            newRow["OutputDirectory"] = folderName;

            newRow["SiteName"] = siteName;
            if (keyValues.ContainsKey("List"))
            {
                newRow["List"] = keyValues["List"];
            }

            if (keyValues.ContainsKey("Folder"))
            {
                newRow["Folder"] = keyValues["Folder"];
            }

            if (keyValues.ContainsKey("Owner"))
            {
                newRow["Owner"] = keyValues["Owner"];
            }
            else
            {
                output = "\r\nSite owner must be specified. " + ((ISPStsadmCommand)this).GetHelpMessage(null);
                return -1;
            }

            if (keyValues.ContainsKey("Contact"))
            {
                newRow["Contact"] = keyValues["Contact"];
            }
            else
            {
                output = "\r\nSite contact (email) must be specified. " + ((ISPStsadmCommand)this).GetHelpMessage(null);
                return -1;
            }

            newRow["includeSubWebs"] = false;
            if (keyValues.ContainsKey("includeSubWebs"))
            {
                newRow["includeSubWebs"] = true;
            }

            newRow["includeUserInformation"] = false;
            if (keyValues.ContainsKey("includeUserInformation"))
            {
                newRow["ExportUsers"] = true;
            }

            newRow["ManagedPath"] = managedPath;
            if (keyValues.ContainsKey("SiteDefinition"))
            {
                newRow["SiteDef"] = keyValues["SiteDefinition"];
            }

            if (keyValues.ContainsKey("MinDate"))
            {
                newRow["ExportItemsNewerThan"] = Convert.ToDateTime(keyValues["MinDate"]);
            }

            if (keyValues.ContainsKey("MaxDate"))
            {
                newRow["ExportItemsOlderThan"] = Convert.ToDateTime(keyValues["MaxDate"]);
            }

            newRow["ExportVersions"] = false;
            if (keyValues.ContainsKey("includeVersionInformation"))
            {
                newRow["ExportVersions"] = true;
            }

            newRow["ExportDoclibsOnly"] = false;
            newRow["ProcessGalleries"] = false;
            newRow["ExportViews"] = false;

            // Add the row to the rows collection.
            dt.Rows.Add(newRow);
            Sharepoint.ImportExport.Extractor.Exporter extractor = new Exporter();
            if (!extractor.Init(false))
            {
                Logger log = new Logger();
                Logger.Init("export" + DateTime.Now.ToString("MMddHHmm") + ".log", level);
                Logger.LogDataSendingEvent += new Logger.LogDataEventHandler(IncomingEventLogData);

                try
                {
                    string resultData = extractor.Process(ds);
                }
                catch
                {
                }
            }

            return 0;
        }

        private static void IncomingEventLogData(object sender, SPEventArgs e)
        {
            string msg = e.Message;
            int pos = msg.IndexOf("-");
            if (pos > 0)
            {
                msg = msg.Substring(pos + 1);
            }

            string logArgs = DateTime.Now.ToLongTimeString() + ":  " + msg;
            logS += logArgs;
            Console.WriteLine(logArgs);
        }
    }
}
